<template lang="pug">
  .CreateAccountModal
    Modal(
      v-model="isShowInvoiceApplyModal"
      :title="createInvoiceModalTitle"
      class-name="vertical-center-modal"
      width="80%"
    )
      .h500.overflow-y-scroll(:class="modalKey != 'makeModal' ? 'has-disabled' : ''")
        Form.ivu-row.has-rules-item2.ivu-form-basic(ref="formData" :model="formData" :rules="rules" :label-width="120")
          FormItem.form-item.ivu-col(v-for="(item, index) of setFormItem" :label="item.label" :key="index" :class="item.style" :prop="item.prop")
            template(v-if="item.type === 'input'")
              Input(v-model="formData[item.model]" :placeholder="modalKey != 'makeModal' ? '未填写' : item.placeholder" :disabled="item.isDisabled" clearable)
            template(v-if="item.type === 'select'")
              Select(v-if="item.fn" v-model="formData[item.model]" :placeholder="modalKey != 'makeModal' ? '未填写' : item.placeholder" clearable filterable :disabled="item.isDisabled || !arrListDown[item.options].length" label-in-value :multiple="item.multiple" :max-tag-count="item.multiple ? 1 : 0" @on-change="(event, type) => listenCall(item.fn, item.model, event)")
                Option(v-for="(c_item, c_index) of arrListDown[item.options]" :key="c_index" :value="c_item.value") {{c_item.label}}
              Select(v-else v-model="formData[item.model]" :placeholder="modalKey != 'makeModal' ? '未填写' : item.placeholder" clearable filterable :disabled="item.isDisabled || !arrListDown[item.options].length" :multiple="item.multiple" :max-tag-count="item.multiple ? 1 : 0")
                Option(v-for="(c_item, c_index) of arrListDown[item.options]" :key="c_index" :value="c_item.value") {{c_item.label}}
            template(v-if="item.type === 'datePicker'")
              DatePicker.w-100(v-if="item.fn" v-model="formData[item.model]" :placeholder="modalKey != 'makeModal' ? '未填写' : item.placeholder" :type="item.mode ? item.mode : 'date'" :disabled="item.isDisabled" @on-change="(event, type) => listenCall(item.fn, item.model, event)")
              DatePicker.w-100(v-else v-model="formData[item.model]" :placeholder="modalKey != 'makeModal' ? '未填写' : item.placeholder" :type="item.mode ? item.mode : 'date'" :disabled="item.isDisabled")
            template(v-if="item.type === 'switch'")
              i-switch(v-model="formData[item.model]")
        
        Divider
          Icon.text-gray-ccc(type="md-cut")

        Form(ref="tableData")
          Row.form-item.mb-10
            Col.text-left.font-14.pl-25(v-for="(title, titleIndex) of thead" :key="titleIndex" :span="title.span") {{title.txt}}
          Row.form-item.mb-10(v-for="(row, rowIndex) of tableData" :key="rowIndex")
            Col.pl-10.pr-10(span="4")
              Input(v-model="row.productDetail" disabled)
            Col.pl-10.pr-10(span="4")
              Input(v-model="row.billAmt" disabled)
            Col.pl-10.pr-10(span="4")
              Input(v-model="row.taxRate" disabled)
            Col.pl-5.pr-10(span="4")
              Select(v-model="row.invoiceTaxName" disabled)
                Option(v-for="(c_item, c_index) of row.invoiceTaxNames" :key="c_index" :value="c_item") {{c_item}}
            Col.pl-10.pr-10(span="4")
              Input(v-model="row.amt" @on-blur="(val) => handleChangeAmt(val, rowIndex)" disabled)
            Col.pl-10.pr-10(span="4")
              Input(v-model="row.restAmt" disabled)
          //- FormItem.form-item.ivu-col(v-for="(item, index) of tableData" :key="index" :prop="item.prop")

      .clearfix(slot="footer")
        Button(type="text" @click="cancel") 取消
        Button(v-show="!(modalKey == 'lookModal')" type="primary" @click="handleSubmit" :loading="!isCanSubmit") 保存
</template>

<script>
import { Common } from '@/utils/common.js'
import _cloneDeep from 'clone-deep'
import { FinanceApi } from '@/api/Finance.api.js'
import { FinanceInvoiceApi } from '@/api/FinanceInvoice.api.js'
import { InvoiceApplyThead } from '../tableHead'

export default {
  name: 'InvoiceApplyModal',

  watch: {
  },

  computed: {
    setFormItem () {
      this.formItem.map(item => {
        if (['invoiceNo', 'redInvoiceNo', 'doTime'].indexOf(item.model) !== -1) {
          item.isDisabled = this.modalKey === 'makeModal' ? false : true
        }
      })
      return this.formItem
    }
  },

  data () {
    return {
      isShowInvoiceApplyModal: false,
      // isCreate: true,
      modalKey: 'makeModal',
      createInvoiceModalTitle: null,
      isCanSubmit: true,
      // thead: _cloneDeep(InvoiceApplyThead),
      thead: [
        {txt: '产品明细', span: 4},
        {txt: '账单金额', span: 4},
        {txt: '税率', span: 4},
        {txt: '税目', span: 4},
        {txt: '开票金额', span: 4},
        {txt: '剩余开票金额', span: 4},
      ],
      tableData: [],
      tableComone: {
        pageIndex: 1,
        totalRows: 0,
        pageSize: 10
      },
      formData: {
        invoiceChannel: '0',
        invoiceID: null,
        parentName: null,
        legalInfos: [],
        applyUser: null,
        applyUserName: null,
        applyTime: null,
        doUser: null,
        doUserName: null,
        doTime: null,
        invoiceNo: null,
        status: 0,

        parentID: null,
        companyInfos: null,
        invoiceManner: '1',
        billType: null,
        // periodYM: null,
        periodYear: null,
        periodMonth: null,
        productType: null,
        invoiceType: null,
        legalName: null,
        creditCode: null,
        address: null,
        phone: null,
        bankName: null,
        bankNo: null,
        invoiceReceiver: null,
        phoneNo: null,
        email: null,
        invoiceDate: null,
        remark: null,
        totalAmt: 0,
        restAmt: 0,
        invoiceNo: null,
        oldInvoiceNo: null,
        returnReason: null,
        redInvoiceNo: null
      },
      formItem: [
        { type: 'select', label: '开票渠道：', placeholder: '请选择开票渠道', prop: 'invoiceChannel', model: 'invoiceChannel', style: 'ivu-col-span-8', options: 'invoiceChannelOps', isDisabled: true, isShow: true },
        { type: 'select', label: '集团公司：', placeholder: '请选择集团公司', prop: 'parentID', model: 'parentID', style: 'ivu-col-span-8', options: 'parentCompanys', fn: 'parentCompanysChange', isDisabled: true  },
        { type: 'select', label: '客户名称：', placeholder: '请选择客户名称', prop: 'companyInfos', model: 'companyInfos', style: 'ivu-col-span-8', options: 'childrenCompanys', fn: 'companyInfosChange', multiple: true, isDisabled: true  },
        { type: 'select', label: '开票方式：', placeholder: '请选择开票方式', prop: 'invoiceManner', model: 'invoiceManner', style: 'ivu-col-span-8', options: 'invoiceMannerList', isDisabled: true },
        { type: 'select', label: '应收账单：', placeholder: '请选择应收账单', prop: 'billType', model: 'billType', style: 'ivu-col-span-8', options: 'billTypeList', isDisabled: true  },
        { type: 'datePicker', label: '费用月份：', placeholder: '请选择费用月份', prop: 'periodYear', model: 'periodYear', style: 'ivu-col-span-8', fn: 'periodChange', mode: 'month', isDisabled: true  },
        { type: 'input', label: '产品类别：', placeholder: '请选择产品类别', prop: 'productType', model: 'productType', style: 'ivu-col-span-8', isDisabled: true },
        { type: 'select', label: '发票类型：', placeholder: '请选择发票类型', prop: 'invoiceType', model: 'invoiceType', style: 'ivu-col-span-8', options: 'invoiceTypeList', isDisabled: true  },
        { type: 'select', label: '名称：', placeholder: '请选择法人名称', prop: 'legalName', model: 'legalName', style: 'ivu-col-span-8', options: 'legalNameList', fn: 'legalNameChange', isDisabled: true  },
        { type: 'input', label: '纳税人识别号：', placeholder: '请输入纳税人识别号', prop: 'creditCode', model: 'creditCode', style: 'ivu-col-span-8', isDisabled: true },
        { type: 'input', label: '地址：', placeholder: '请输入地址', prop: 'address', model: 'address', style: 'ivu-col-span-8', isDisabled: true },
        { type: 'input', label: '电话：', placeholder: '请输入电话', prop: 'phone', model: 'phone', style: 'ivu-col-span-8', isDisabled: true },
        { type: 'input', label: '开户行：', placeholder: '请输入开户行', prop: 'bankName', model: 'bankName', style: 'ivu-col-span-8', isDisabled: true },
        { type: 'input', label: '银行账号：', placeholder: '请输入银行账号', prop: 'bankNo', model: 'bankNo', style: 'ivu-col-span-8', isDisabled: true },
        { type: 'input', label: '发票接收人：', placeholder: '请输入发票接收人', prop: 'invoiceReceiver', model: 'invoiceReceiver', style: 'ivu-col-span-md-24 ivu-col-span-lg-12 ivu-col-span-xl-12 ivu-col-span-xxl-8', isDisabled: true, isShow: true },
        { type: 'input', label: '手机号码：', placeholder: '请输入手机号码', prop: 'phoneNo', model: 'phoneNo', style: 'ivu-col-span-md-24 ivu-col-span-lg-12 ivu-col-span-xl-12 ivu-col-span-xxl-8', isDisabled: true, isShow: true },
        { type: 'input', label: '邮箱：', placeholder: '请输入邮箱', prop: 'email', model: 'email', style: 'ivu-col-span-md-24 ivu-col-span-lg-12 ivu-col-span-xl-12 ivu-col-span-xxl-8', isDisabled: true, isShow: true },
        { type: 'datePicker', label: '申请开票日期：', placeholder: '请选择申请开票日期', prop: 'invoiceDate', model: 'invoiceDate', style: 'ivu-col-span-8', fn: 'periodChange', isDisabled: true  },
        { type: 'input', label: '开票说明：', placeholder: '请输入开票说明', prop: 'remark', model: 'remark', style: 'ivu-col-span-8', isDisabled: true  },
        { type: 'input', label: '开票金额：', placeholder: '请输入开票金额', prop: 'totalAmt', model: 'totalAmt', style: 'ivu-col-span-8', isDisabled: true },
        { type: 'input', label: '待开票金额：', placeholder: '请输入待开票金额', prop: 'restAmt', model: 'restAmt', style: 'ivu-col-span-8', isDisabled: true },
        { type: 'input', label: '申请人：', placeholder: '请输入申请人', prop: 'applyUserName', model: 'applyUserName', style: 'ivu-col-span-8', isDisabled: true },
        { type: 'datePicker', label: '申请时间：', placeholder: '请输入申请时间', prop: 'applyTime', model: 'applyTime', style: 'ivu-col-span-8', isDisabled: true },
        { type: 'input', label: '开票人：', placeholder: '请输入开票人', prop: 'doUserName', model: 'doUserName', style: 'ivu-col-span-8', isDisabled: true },
        { type: 'datePicker', label: '开票时间：', placeholder: '请输入开票时间', prop: 'doTime', model: 'doTime', style: 'ivu-col-span-8', isDisabled: false },
        { type: 'input', label: '发票号码：', placeholder: '请输入发票号码', prop: 'invoiceNo', model: 'invoiceNo', style: 'ivu-col-span-8', isDisabled: false  },
        { type: 'input', label: '发票状态：', placeholder: '请输入发票状态', prop: 'status', model: 'status', style: 'ivu-col-span-8', options: 'status', isDisabled: true  },
        // { type: 'input', label: '原开票：', placeholder: '请输入原开票', prop: 'oldInvoiceNo', model: 'oldInvoiceNo', style: 'ivu-col-span-8', isDisabled: true },
        { type: 'input', label: '退换票原因：', placeholder: '请输入退换票原因', prop: 'returnReason', model: 'returnReason', style: 'ivu-col-span-8', isDisabled: true  },
        // { type: 'input', label: '红字发票：', placeholder: '请输入红字发票', prop: 'redInvoiceNo', model: 'redInvoiceNo', style: 'ivu-col-span-8', isDisabled: false },
      ],
      rules: {
        invoiceNo: [
          { required: true, message: '请输入发票号码', trigger: 'change' }
        ],
        // redInvoiceNo: [
        //   { required: true, message: '请输入红字发票', trigger: 'change' }
        // ]
      },
      arrListDown: {
        parentCompanys: [],
        childrenCompanys: [],
        status: [],
        billTypeList: [{ label: 'HRO', value: 'HRO' }],
        // defaultOps: [
        //   { label: '是', value: '1' },
        //   { label: '否', value: '0' }
        // ],
        invoiceTypeList: [
          { label: '增值税专用发票', value: '增值税专用发票' },
          { label: '增值税普通发票', value: '增值税普通发票' },
          { label: '电子发票-普票', value: '电子发票-普票' },
        ],
        invoiceMannerList: [
          { label: '实发开票', value: '0' },
          { label: '应发开票', value: '1' },
        ],
        invoiceChannelOps: [
          { label: '账单开票', value: '0' },
          { label: '即时开票', value: '1' },
        ],
        legalNameList: [],
        legalNameListInit: [], // 法人原始下拉列表
      },
      selectedParentCompany: {}, // 选中的集团
      selectedCompanyInfo: [], // 选中的客户
      selectedLegal: {}, // 选中的法人
    }
  },

  mounted () {
    this.getParentCompanys()
  },

  methods: {
    // 监听所有调用的方法
    listenCall (methodsWords, ...values) {
      this[methodsWords](...values)
    },

    // 数据字典-获取集团公司
    getParentCompanys () {
      Common.getParentCompanys(this.arrListDown, 'parentCompanys')
    },

    cancel () {
      this.isShowInvoiceApplyModal = false
    },

    show () {
      this.isCanSubmit = true
      this.isShowInvoiceApplyModal = true
      this.$refs.formData.resetFields({})
      this.tableData = []
      console.log('点击是的show()')
      console.log('this.formData: ', this.formData)
      console.log('this.$refs.formData: ', this.$refs.formData)
    },

    // 提交表单
    handleSubmit () {
      var params = {
        InvoiceID: this.formData.invoiceID,
        InvoiceNo: this.formData.invoiceNo,
        RedInvoiceNo: this.formData.redInvoiceNo,
        doTime: this.formData.doTime
      }
      this.$refs.formData.validate((valid) => {
        if (valid) {
          this.isCanSubmit = false
          FinanceInvoiceApi.invoice(params).then(resp=>{
            if (resp.data.success) {
              this.$Message.success(resp.data.message)
              this.isShowInvoiceApplyModal = false
              this.$emit('query')
            } else {
              this.isCanSubmit = true
              this.$Message.error(resp.data.message)
            }
          })
        } else {
          this.isCanSubmit = true
          this.$Message.warning('输入有误，请返回检查!')
        }
      })
    },

    // 根据ID获取信息
    async getModel (id) {
      var params = {
        InvoiceID: id
      }
      let resp = await FinanceInvoiceApi.getInvoiceInfo(params)

      if (resp.status === 200 && resp.data.success) {
        this.show()
        var result = resp.data.data

        // 表格处理
        var restAmtTotal = 0
        result.details.map(row => {
          // row.restAmt = row.billAmt - row.amt    // 初始化数据时resetAmt已是计算后的结果，只有编辑开票金额才要重新计算剩余开票金额
          restAmtTotal += row.restAmt
          if (row.invoiceTaxNames.length) {
            row.invoiceTaxName = row.invoiceTaxNames[0]
          }
        })
        this.tableData = result.details

        // 法人名称下拉列表
        var legalNameList = []
        this.legalNameListInit = result.legalInfos
        result.legalInfos.map(legal => {
          legalNameList.push({value: legal.creditCode, label: legal.legalName})
        })
        this.arrListDown.legalNameList = legalNameList

        // 相应赋值
        Object.keys(this.formData).forEach(key => {
          var tempArr = ['periodYear', 'companyInfos', 'legalName']
          if (tempArr.indexOf(key) < 0) {
            this.formData[key] = result[key]
          }
        })

        // this.formData.invoiceDate = this.$moment(result.invoiceDate).format('YYYY-MM-dd')


        // 费用月份
        var periodMonth = +result.periodMonth < 10 ? '0' + result.periodMonth : result.periodMonth
        this.formData.periodYear = result.periodYear + '-' + periodMonth

        this.selectedParentCompany = {value: result.parentID, label: result.parentName}

        // 客户名称 
        this.formData.companyInfos = result.companyInfos.map(item => {return item.companyID})

        // 法人名称
        this.selectedLegal = result.legalInfos.find(item => {return item.creditCode === result.creditCode})
        this.formData.legalName = this.selectedLegal?this.selectedLegal.creditCode:''

        // 客户名称
        this.selectedCompanyInfo = []
        result.companyInfos.map(item => {
          this.selectedCompanyInfo.push({value: item.companyID, label: item.companyName}) // 选中的客户=接口返回的
          this.arrListDown.childrenCompanys.push({value: item.companyID, label: item.companyName})
        })

        // 开票时间
        this.formData.doTime = this.$moment(this.modalKey=='lookModal'?result.doTime:new Date()).format('YYYY-MM-DD')
        // this.formData.doTime = this.$moment().format('YYYY-MM-DD')    // bug:导致开票时间一直展示当前时间
        

        if (this.modalKey == 'makeModal') {
          this.formData.invoiceNo = null
        }

        // 待开票金额
        this.formData.restAmt = result.restAmt
        setTimeout(() => {
          this.formData.invoiceChannel = result.invoiceChannel + ''
          this.formData.invoiceManner = result.invoiceManner + ''
          this.formData.remark = result.remark
          this.formData.phoneNo = this.selectedLegal.phoneNo ? this.selectedLegal.phoneNo : null
          this.formData.email = this.selectedLegal.email ? this.selectedLegal.email : null
          this.formData.invoiceReceiver = this.selectedLegal.invoiceReceiver ? this.selectedLegal.invoiceReceiver : null
        }, 500);
      } else {
        this.$Message.error({
          content: resp.data.message,
          duration: 10,
          closable: true
        })
      }
    },

    // 获取所有集团下的公司-1
    parentCompanysChange (model, event) {
      console.log('获取所有集团下的公司 model: ', model, ', event: ', event)
      console.log('this.formData[model]: ', this.formData[model])
      if (event && event.value) {
        this.selectedParentCompany = event
        console.log('选中的集团 selectedParentCompany: ', this.selectedParentCompany)
        FinanceApi.getAllChildCompanys({companyGuid: event.value}).then(resp => {
          console.log('获取所有集团下的公司: ', resp)
          var arr = []
          if (resp.status == 200 && resp.data) {
            resp.data.map(item => {
              if (item.group == 'customer') {
                item.items.map(c_item => {
                  arr.push({label: c_item.value, value: c_item.key})
                })
              }
            })
            this.arrListDown.childrenCompanys = arr
          }
        })
      }
    },

    // 客户名称选择改变-2
    companyInfosChange (model, event) {
      console.log('2 客户名称选择改变 model: ', model, ', event: ', event)
      console.log('2 this.formData[model]: ', this.formData[model])
      if (event) {
        this.selectedCompanyInfo = event
        // this.getAddResponse()
      }
    },

    // 费用月份选择改变
    periodChange (model, event) {
      console.log('费用月份选择改变 model: ', model, ', event: ', event)
      this.formData[model] = event
      if (model === 'periodYear') {
        // this.getAddResponse()
        // this.formData.periodYear
      }
    },

    // 获取发票申请数据
    // getAddResponse () {
    //   var companyInfosArr = []
    //   this.selectedCompanyInfo.map(item => {
    //     companyInfosArr.push({CompanyID: item.value, CompanyName: item.label})
    //   })

    //   if (this.modalKey === 'makeModal' && this.selectedParentCompany && this.formData.periodYear && this.formData.billType) {
    //     var params = {
    //       ParentID: this.selectedParentCompany.value,
    //       ParentName: this.selectedParentCompany.label,
    //       CompanyInfos: companyInfosArr,
    //       PeriodYear: this.$moment(this.formData.periodYear).format('YYYY'),
    //       PeriodMonth: this.$moment(this.formData.periodYear).format('MM'),
    //       BillType: this.formData.billType,
    //     }
    //     console.log('❤ params: ', params)

    //     FinanceInvoiceApi.getAddResponse(params).then(resp => {
    //       console.log('获取发票申请数据: ', resp)
    //       // 客户名称为多选时，开票金额=账单金额且禁用
    //       if (resp.status == 200 && resp.data.success) {
    //         var result = resp.data.data

    //         // 初始默认税目
    //         result.details.map(row => {
    //           row.amt = this.selectedCompanyInfo.length > 1 ? row.billAmt : row.amt // 选择客户数量有多个时，开票金额=账单金额
    //           row.restAmt = this.selectedCompanyInfo.length > 1 ? 0 : row.billAmt // 选择客户数量有多个时，剩余金额=0
    //           if (row.invoiceTaxNames.length) {
    //             row.invoiceTaxName = row.invoiceTaxNames[0]
    //           }
    //         })
    //         this.tableData = result.details

    //         // 法人名称下拉列表
    //         var legalNameList = []
    //         this.legalNameListInit = result.legalInfos
    //         result.legalInfos.map(legal => {
    //           legalNameList.push({value: legal.creditCode, label: legal.legalName})
    //         })
    //         this.arrListDown.legalNameList = legalNameList
    //         console.log('this.arrListDown.legalNameList: ', this.arrListDown.legalNameList)

    //         // 相应赋值
    //         Object.keys(this.formData).forEach(key => {
    //           var tempArr = ['parentID', 'companyInfos', 'billType', 'periodYear', 'invoiceType', 'invoiceDate', 'remark', 'legalName']
    //           if (tempArr.indexOf(key) < 0) {
    //             this.formData[key] = result[key]
    //           }
    //         })
    //       } else {
    //         this.$Message.error(resp.data.message)

    //         this.tableData = []
    //         this.legalNameListInit = []
    //         this.arrListDown.legalNameList = []

    //         // 清空相应赋值
    //         Object.keys(this.formData).forEach(key => {
    //           var tempArr = ['parentID', 'companyInfos', 'billType', 'periodYear', 'invoiceType', 'remark']
    //           if (tempArr.indexOf(key) < 0) {
    //             this.formData[key] = ''
    //           }
    //         })
    //       }
    //     })
    //   }
    // },

    // 法人名称选择改变
    legalNameChange (model, event) {
      if (event && event.value) {
        this.selectedLegal = this.legalNameListInit.find(item => {return item.creditCode === event.value})
        
        // 相应赋值
        this.formData.creditCode = this.selectedLegal.creditCode
        this.formData.address = this.selectedLegal.address
        this.formData.phone = this.selectedLegal.phone
        this.formData.bankName = this.selectedLegal.bankName
        this.formData.bankNo = this.selectedLegal.bankNo
      }
    },

    // 表格里的开票金额下拉选择
    handleChangeInvoiceTaxName (val, index) {
      console.log('表格里的开票金额下拉选择 val: ', val, ', index: ', index)
      this.tableData[index].invoiceTaxName = val
    },

    // 表格里的剩余开票金额输入改变
    handleChangeAmt (val, rowIndex) {
      console.log('表格里的剩余开票金额输入改变 val: ', val, ', rowIndex: ', rowIndex)
      if (+val.target.value > +this.tableData[rowIndex].billAmt) {
        this.$Message.warning('开票金额不能大于账单金额')
        this.tableData[rowIndex].amt = 0
        this.tableData[rowIndex].restAmt = this.tableData[rowIndex].billAmt
      } else {
        this.tableData[rowIndex].restAmt = this.tableData[rowIndex].billAmt - this.tableData[rowIndex].amt
        this.formData.totalAmt = 0
        this.formData.restAmt = 0
        this.tableData.map(row => {
          this.formData.totalAmt += +row.amt
          this.formData.restAmt += +row.restAmt
        })
      }
    },
  }
}
</script>

<style lang="less" scoped>

</style>
